/*
 * @lc app=leetcode.cn id=395 lang=javascript
 *
 * [395] 至少有 K 个重复字符的最长子串
 */

// @lc code=start
/**
 * @param {string} s
 * @param {number} k
 * @return {number}
 */

// 分而治之
var longestSubstring = function(s, k) {
  let map = {}
  for (let char of s) {
    map[char] = map[char] ? map[char] + 1 : 1;
  }
  let splits = [];
  for (let i = 0; i < s.length; i++) {
    if(map[s[i]] < k) splits.push(i);
  }
  splits.push(s.length);
  if(splits.length === 1) return s.length;  

  let pre = 0; let max = 0;
  for (let i = pre; i < splits.length; i++) {
    let len = splits[i] - pre;
    max = Math.max(longestSubstring(s.substr(pre, len), k), max);
    pre = splits[i] + 1;
  }
  return max;
};
// @lc code=end

